<template>
  <div id="app">
    <Header 
      v-if="isAuthenticated" 
      :currentChatTitle="currentChat.title"
      @toggle-history="toggleHistoryPanel"
      @logout="handleLogout"
    />
    
    <div class="main-container">
      <!-- 未登录状态显示登录/注册 -->
      <div v-if="!isAuthenticated" class="auth-container">
        <Login 
          v-if="currentView === 'login'" 
          @switch-to-register="switchView('register')" 
          @login-success="handleLoginSuccess" 
        />
        <Register 
          v-else 
          @switch-to-login="switchView('login')" 
          @register-success="handleRegisterSuccess" 
        />
      </div>
      
      <!-- 已登录状态显示聊天界面 -->
      <div v-else class="chat-layout">
        <HistoryPanel 
          :class="{ 'history-open': historyOpen }"
          :chatHistory="chatHistory" 
          @load-chat="loadChatHistory"
          @new-chat="startNewChat"
          @close="historyOpen = false"
        />
        
        <ChatWindow 
          :currentChat="currentChat"
          @send-message="sendMessage"
          @save-chat="saveChatHistory"
          @toggle-history="toggleHistoryPanel"
        />
      </div>
    </div>
  </div>
</template>

<script>
import Header from './components/Header.vue'
import Login from './components/Login.vue'
import Register from './components/Register.vue'
import ChatWindow from './components/ChatWindow.vue'
import HistoryPanel from './components/HistoryPanel.vue'
import { auth } from './utils/auth'

export default {
  name: 'App',
  components: {
    Header,
    Login,
    Register,
    ChatWindow,
    HistoryPanel
  },
  data() {
    return {
      currentView: 'login',
      isAuthenticated: auth.isAuthenticated(),
      historyOpen: false,
      chatHistory: JSON.parse(localStorage.getItem('chatHistory') || '[]'),
      currentChat: {
        id: null,
        title: '新对话',
        messages: []
      }
    }
  },
  created() {
    if (this.isAuthenticated) {
      this.loadChatHistory();
    }
  },
  methods: {
    switchView(view) {
      this.currentView = view;
    },
    
    handleLoginSuccess() {
      this.isAuthenticated = true;
      this.loadChatHistory();
    },
    
    handleRegisterSuccess() {
      this.isAuthenticated = true;
      this.startNewChat();
    },
    
    handleLogout() {
      auth.logout();
      this.isAuthenticated = false;
      this.currentView = 'login';
      this.startNewChat();
    },
    
    toggleHistoryPanel() {
      this.historyOpen = !this.historyOpen;
    },
    
    sendMessage(message) {
      if (!this.currentChat.id) {
        this.currentChat.id = Date.now();
        this.currentChat.title = message.content.length > 20 
          ? message.content.substring(0, 20) + '...' 
          : message.content;
      }
      
      this.currentChat.messages.push({
        id: Date.now(),
        sender: 'user',
        content: message.content,
        timestamp: new Date()
      });

      // 设置加载状态
      this.isLoading = true;

      
      // 模拟AI回复
      setTimeout(() => {
        this.currentChat.messages.push({
          id: Date.now(),
          sender: 'ai',
          content: this.generateAIResponse(message.content),
          timestamp: new Date()
        });
        
        this.saveChatHistory();
        this.isLoading = false;
      }, 1000 + Math.random() * 1000);
    },
    
    generateAIResponse(userMessage) {
      const responses = [
        "这是一个很好的问题！让我来为您详细解答...",
        "根据您的描述，我建议可以这样处理...",
        "这个问题可以从多个角度来分析。首先...",
        "我理解您的需求。实际上，这个问题可以这样解决...",
        "感谢您的提问！关于这个问题，我的建议是...",
        "让我思考一下如何最好地回答您的问题...",
        "基于我的知识，我可以告诉您...",
        "这个问题很有趣！让我为您提供一些见解..."
      ];
      return responses[Math.floor(Math.random() * responses.length)];
    },
    
    saveChatHistory() {
      if (!this.currentChat.id) return;
      
      const existingIndex = this.chatHistory.findIndex(chat => chat.id === this.currentChat.id);
      
      if (existingIndex >= 0) {
        this.chatHistory[existingIndex] = { ...this.currentChat };
      } else {
        this.chatHistory.unshift({ ...this.currentChat });
      }
      
      localStorage.setItem('chatHistory', JSON.stringify(this.chatHistory));
    },
    
    loadChatHistory(chatId = null) {
      if (chatId) {
        const chat = this.chatHistory.find(c => c.id === chatId);
        if (chat) {
          this.currentChat = JSON.parse(JSON.stringify(chat));
        }
      } else if (this.chatHistory.length > 0) {
        this.currentChat = JSON.parse(JSON.stringify(this.chatHistory[0]));
      } else {
        this.startNewChat();
      }
      this.historyOpen = false;
    },
    
    startNewChat() {
      this.currentChat = {
        id: null,
        title: '新对话',
        messages: []
      };
      this.historyOpen = false;
    }
  }
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

body {
  background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
  color: #e2e8f0;
  min-height: 100vh;
}

#app {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-container {
  flex: 1;
  display: flex;
}

.auth-container {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.chat-layout {
  flex: 1;
  display: flex;
  height: calc(100vh - 60px);
  position: relative;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .auth-container {
    padding: 10px;
  }
}
</style>